package cn.jiadakeji.parent.common.util;

import cn.jiadakeji.parent.common.constant.WechatConstants;
import cn.jiadakeji.parent.dto.WechatSubscribeRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class WechatUtils {
    private final static Logger logger = LoggerFactory.getLogger(WechatUtils.class);

    public static JSONObject jscode2session(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<String, String>();
        param.put("appid", WechatConstants.APPID);
        param.put("secret",WechatConstants.SECRET);
        param.put("js_code",code);
        param.put("grant_type",WechatConstants.GRANT_TYPE);
        logger.info("开始jscode2session");
        String wxResult = OKHttp3Utils3.get(url, param);
        logger.info(wxResult);
        return  JSON.parseObject(wxResult);
    }


    public static String getWechatAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, String> param = new HashMap<String, String>();
        param.put("grant_type","client_credential");
        param.put("appid", WechatConstants.APPID);
        param.put("secret",WechatConstants.SECRET);
        String wxResult = OKHttp3Utils3.get(url, param);
        System.out.println(wxResult);
        JSONObject jsonObject = JSON.parseObject(wxResult);
        if(jsonObject.containsKey("access_token")){

            return jsonObject.getString("access_token");
        }
        return null;
    }

    public static void sendWeChatSubscribeMessage(String token, WechatSubscribeRequest prams){
        String url = WechatConstants.SUBSCRIBE_MESSAGE_SEND_URL+"?access_token="+token;
        logger.info("-----发送啦------");
        String pa = JSONObject.toJSONString(prams);
        logger.info(pa);
        String res = OKHttp3Utils3.post(url, pa);
       logger.info("------this is send message res -----");
       logger.info(res);
    }
}
